﻿using System;
using System.Messaging;

namespace NsbMonitorClientService.QueueManager
{
    public class FetchOldestMessageTime : IFetchOldestMessageTime
    {
        public DateTime? OldestMessageTime(MessageQueue messageQueue)
        {
            try
            {
                MessagePropertyFilter propertyFilter = (MessagePropertyFilter)messageQueue.MessageReadPropertyFilter.Clone();
                messageQueue.MessageReadPropertyFilter.SetAll();
                Message message = messageQueue.Peek(new TimeSpan(0));

                messageQueue.MessageReadPropertyFilter = propertyFilter;

                if (message == null)
                {
                    return null;
                }

                return message.SentTime;

            }
            catch (MessageQueueException mqe)
            {
                if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
                {
                    throw;
                }
            }


            return null;
        }
    }
}